<?php
class GuestbookModel extends Model {
	public function __construct() {
		parent::__construct('Guestbook');
	}
	
	public function getOneByPk($id, $field = '*') {
		return $this->field($field)->where('id='.$id)->find();
	}
	
	public function addOne(& $data) {
		return $this->data($data)->add();
	}
	
	// 留言正序排列
	public function getListByPage($pageSize = 10) {
		import('ORG.Util.Page');
		$pre = C('DB_PREFIX');
		
		$where = 'pid=0 and tongguo=1';
		$count = $this->where($where)->count();	
		if(empty($count)) $count = 0;
		$page = new Page($count, $pageSize);
		$pageString = $page->show();
		
		$sql = 'select id,nickname,email,website,content,avatar,posttime'.
			" from {$pre}guestbook".
			" where {$where} and id>=(select id from {$pre}guestbook order by id asc limit {$page->firstRow},1) order by id asc limit {$pageSize}";
			
		$data = $this->query($sql);
		//var_dump($this->getLastsql()); exit;
		
		
		if(is_array($data)) {
			$this->processSubComment($data);
		}
		
		$data['pageString'] = $pageString;
		
		return $data;
	}
	
	public function processSubComment(& $data) {
		$pre = C('DB_PREFIX');
		for($i=0, $len=count($data); $i<$len; $i++) {
			$data[$i]['sub'] = $this->query("select id,nickname,email,website,content,avatar,posttime from {$pre}guestbook where tongguo=1 and pid={$data[$i]['id']}");
		}
	}
}